package com.qf.service.impl;


import com.qf.client.PicShareClient;
import com.qf.dao.UserMapper;
import com.qf.dao.UserRepository;
import com.qf.pojo.BaseResp;
import com.qf.pojo.TbUser;
import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.utils.CookieUtils;
import com.qf.utils.JWTutils;
import com.qf.utils.MD5Utils;
import com.qf.utils.RedisUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;


import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    RedisUtils redisUtils;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    JavaMailSender javaMailSender;
    @Autowired
    UserRepository userRepository;
    @Autowired
    UserMapper userMapper;
    @Autowired
    PicShareClient picShareClient;
    @Value("${spring.mail.username}")//从xml中
    private String myEmail;



    @Override
    public BaseResp login(User user) {
        BaseResp baseResp = new BaseResp();
        if(user==null){
            baseResp.setCode(201);
            baseResp.setMessage("请输入用户名密码");
            return baseResp;
        }
        //查询用户名是否存在
        User byUserName = userRepository.findByUserName(user.getUserName());

        if (byUserName==null){
            baseResp.setCode(201);
            baseResp.setMessage("用户名不存在");
            return baseResp;
        }
        //MD5加密对比数据库密码
        MD5Utils md5Utils = new MD5Utils();
        String md5 = md5Utils.getMD5(user.getPassword());
        if (!md5.equals(byUserName.getPassword())){
            baseResp.setCode(201);
            baseResp.setMessage("密码输入有误");
            return baseResp;
        }
        Map map = new HashMap<>();
        map.put("userName",byUserName.getUserName());
        map.put("id",byUserName.getId());
        //加密
        JWTutils jwTutils = new JWTutils();
        String token = jwTutils.securtToken(map);
        UUID uuid = UUID.randomUUID();
        redisUtils.set(uuid.toString(),token);
        baseResp.setCode(200);
        baseResp.setMessage("登录成功");
        baseResp.setData(uuid);
        return baseResp;
    }

    @Override
    public BaseResp regisry(TbUser tbUser) {
        BaseResp baseResp = new BaseResp();
        //查询用户名是否存在
        User byUserName = userRepository.findByUserName(tbUser.getUserName());
        //验证码与存入reids验证码对比
        Object o = redisUtils.get(tbUser.getEmail());
        if (o==null|| !tbUser.getCode().equals(o.toString())){
            baseResp.setCode(201);
            baseResp.setMessage("验证码已过期");
            return baseResp;
        }
        if (byUserName!=null){
            baseResp.setCode(201);
            baseResp.setMessage("登录账号已存在");
            return baseResp;
        }
        //对密码进行MD5加密
        MD5Utils md5Utils = new MD5Utils();
        String password = md5Utils.getMD5(tbUser.getPassword());
        tbUser.setPassword(password);

        tbUser.setPic("https://p3-bcy.byteimg.com/img/banciyuan/bcy-static/756c92ab94764b349f44dd0b3790a78a.png~tplv-banciyuan-ivs.image");
        tbUser.setPic1("https://sf1-scmcdn-tos.pstatp.com/goofy/bcy/image/default_banner.c6e8da.jpg");
        User user = new User();
        BeanUtils.copyProperties(tbUser,user);

       userRepository.saveAndFlush(user);
        baseResp.setCode(200);
        baseResp.setMessage("注册成功");
        return baseResp;
    }

    @Override
    public BaseResp sendEmail(String email) {
        BaseResp baseResp = new BaseResp();
        if (email==null){
            baseResp.setCode(201);
            baseResp.setMessage("请输入正确的邮箱号");
            return baseResp;
        }
        //判定eamil是否唯一

        User byEmail = userRepository.findByEmail(email);
        if(byEmail!=null){
            baseResp.setCode(201);
            baseResp.setMessage("邮箱号已存在");
            return baseResp;
        }
        //发送验证码
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = null;

        try {
            mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(myEmail);
            mimeMessageHelper.setTo(email);
            mimeMessageHelper.setSubject("半次元空间注册码");
            //随机生成注册码
            Random random = new Random();
            //拼接
            StringBuffer stringBuffer = new StringBuffer();
            for(int i =0;i<4;i++){
                stringBuffer.append(random.nextInt(10));
            }
            //发送
            mimeMessageHelper.setText("<font style='color:red'>半次元空间频道注册码：</font>"+stringBuffer.toString(),true);
            javaMailSender.send(mimeMessage);
            redisUtils.set(email,stringBuffer.toString(),1800);
            baseResp.setCode(200);
            baseResp.setMessage("邮件发送成功");
            return baseResp;
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return baseResp;
    }

    @Override
    public BaseResp findUserById(HttpServletRequest request) {
        BaseResp baseResp = new BaseResp();
        Integer userId = getUserId(request);
        Optional<User> byId = userRepository.findById(userId);
        if (byId.isPresent()){//!null
            baseResp.setCode(200);
            baseResp.setMessage("查询成功");
            baseResp.setData(byId.get());
            return baseResp;
        }else {
            baseResp.setCode(201);
            baseResp.setMessage("查询失败");
            return baseResp;
        }
    }

    @Override
    public BaseResp findFansAll(HttpServletRequest request) {
        BaseResp baseResp = new BaseResp();
        Integer userId = getUserId(request);
        List<User> users = userMapper.selectAll(userId);
        if (users!=null){//!null
            baseResp.setCode(200);
            baseResp.setMessage("查询成功");
            baseResp.setData(users);
            return baseResp;
        }else {
            baseResp.setCode(201);
            baseResp.setMessage("查询失败");
            return baseResp;
        }
    }

    @Override
    public BaseResp findUserByToId(Integer id) {
        BaseResp baseResp = new BaseResp();
        Optional<User> byId = userRepository.findById(id);
        if (byId.isPresent()){//!null
            baseResp.setCode(200);
            baseResp.setMessage("查询成功");
            baseResp.setData(byId.get());
            return baseResp;
        }else {
            baseResp.setCode(201);
            baseResp.setMessage("查询失败");
            return baseResp;
        }
    }

    @Override
    public BaseResp findUserShareByUid(HttpServletRequest request) {
        //解析获取id
        Integer userId = getUserId(request);
        return picShareClient.findUserShareByUid(userId);
    }
        //用户数据修改
    @Override
    public BaseResp updateUser(User user) {
        BaseResp baseResp = new BaseResp();
        User user1 = userRepository.saveAndFlush(user);
        if (user1==null){
            baseResp.setCode(201);
            baseResp.setMessage("修改失败");
            return baseResp;
        } baseResp.setCode(200);
        baseResp.setMessage("修改成功");
        baseResp.setData(user1);
        return baseResp;
    }

    @Override
    public BaseResp delePicShare(Map map) {
        return picShareClient.delePicShare(map);
    }

    @Override
    public BaseResp outlogin(HttpServletRequest request) {
        BaseResp baseResp = new BaseResp();
        CookieUtils cookieUtils = new CookieUtils();
        String token = cookieUtils.getToken(request);
        redisUtils.del(token);
        baseResp.setCode(200);
        baseResp.setMessage("退出成功");
        return baseResp;
    }

    //根据前端传来的token解析获得id，进行用户资料查询
    public  Integer getUserId(HttpServletRequest request){
        CookieUtils cookieUtils = new CookieUtils();
        String token = cookieUtils.getToken(request);
        Object o = redisUtils.get(token);
        //JWT解析
        JWTutils jwTutils = new JWTutils();
        Map verifier = jwTutils.Verifier(o.toString());
        return Integer.valueOf(verifier.get("id").toString());
    }
}
